<?php
/**
 * Created by PhpStorm.
 * User: Jochen
 * Date: 2017/1/5
 * Time: 上午10:39
 */

namespace EWeiLink\JuPai;

use EWeiLink\JuPai\Console\EnvConfigure;
use Illuminate\Support\ServiceProvider;


class JPServiceProvider extends ServiceProvider
{
    static function make()
    {
        return new JuPai;
    }
    /**
     * APP启动时需要注入的内容
     */
    public function boot()
    {
        $this->loadViewsFrom(__DIR__.'/../resources/views', 'jp');
        if ($this->app->runningInConsole()) {
            $this->install();
        }
        else {
        }
    }

    public function map()
    {
        JuPai::routes();
    }

    public function register()
    {
        // 注册插件工厂类
        $this->app->singleton('App\Plugin', function(){
           return new JuPai();
        });
        // 注册插件的数据库配置
        $this->addDbConnectionConfig();

    }    

    protected function install()
    {
        // 发布模板
        $this->publishes([
            __DIR__.'/../resources/views' => base_path('resources/views/vendor/jp'),
        ], 'jp-views');

        // 发布js
        $this->publishes([
            __DIR__.'/../resources/assets/js' => base_path('resources/assets/js/jp'),
        ], 'jp-react');
        
        // 注册配置文件env
        $this->commands([
            EnvConfigure::class
        ]);
    }

    /**
     * 根据系统默认的数据库配置，更换database为插件的名称
     */
    protected function addDbConnectionConfig()
    {
        // 获取系统默认数据库配置，默认: mongodb
        $default = config('database.default', 'mongodb');
        // 获取默认配置的详细配置信息
        $config = config("database.connections.$default", null);
        assert(!is_null($config), 'database config not found');
        // 决定本插件的链接名称
        $key = 'database.connections.' . JuPai::plugin_database_name;
        $plugin = $this->app->make('App\Plugin');
        // 写入配置
        config([$key => $plugin->connectionConfig($config)]);
    }
}